"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.recordingRouter = void 0;
const express_1 = __importDefault(require("express"));
const log4js_1 = require("log4js");
const ClassroomEntity_1 = require("../entity/ClassroomEntity");
const MediaEntity_1 = require("../entity/MediaEntity");
const Classrooms_1 = require("../../lib/Classrooms");
const utils = __importStar(require("../api-helper"));
const media_1 = require("./media");
const logger = (0, log4js_1.getLogger)('route/room');
const createRoom = utils.create(ClassroomEntity_1.ClassroomEntity, 'classId');
const updateRoom = utils.update(ClassroomEntity_1.ClassroomEntity, 'classId');
function recordingRouter(app) {
    const roomRouter = express_1.default.Router();
    roomRouter.post('/create', async ({ body }, res) => {
        logger.debug('Create room: ' + JSON.stringify(body, null, 2));
        const { classId, mediaConstraints } = body;
        let dbClassroom;
        try {
            if (classId) {
                dbClassroom = await ClassroomEntity_1.ClassroomEntity.findOne({ where: { classId } });
                if (dbClassroom) {
                    res.status(200).send({ result: 'Error', message: 'classroom already Created!' });
                    return;
                }
            }
            if (!dbClassroom) {
                dbClassroom = Object.assign(new ClassroomEntity_1.ClassroomEntity(), body);
                if (mediaConstraints) {
                    let dbMediaConstraints = Object.assign(new MediaEntity_1.MediaConstraintEntity(), (0, media_1.createConstraint)(mediaConstraints));
                    dbMediaConstraints.createTime = Date.now().toString();
                    dbMediaConstraints.lastActiveTime = Date.now().toString();
                    dbClassroom.mediaConstraints = dbMediaConstraints;
                }
                console.log('classroom/create: => ', dbClassroom);
                dbClassroom.createTime = Date.now().toString();
                dbClassroom.lastActiveTime = Date.now().toString();
                dbClassroom = await dbClassroom.save();
            }
            res.status(200).send({ result: 'OK', data: dbClassroom });
        }
        catch (error) {
            console.error(error);
            res.status(200).send({ result: 'Error', message: error });
        }
    });
    roomRouter.post('/update', async ({ body }, res) => {
        logger.debug('Update room: ' + JSON.stringify(body, null, 2));
        const { classId } = body;
        let dbClassroom;
        if (classId) {
            try {
                dbClassroom = await ClassroomEntity_1.ClassroomEntity.findOne({ where: { classId } });
                if (dbClassroom) {
                    Object.assign(dbClassroom, body);
                    dbClassroom = dbClassroom.save();
                }
            }
            catch (error) {
                res.status(200).send({ result: 'Error', message: error.message });
            }
        }
        if (dbClassroom) {
            res.status(200).send({ result: 'OK', data: dbClassroom });
        }
        else {
            res.status(200).send({ result: 'Error', message: 'classroom are not fined!' });
        }
    });
    roomRouter.get('/list', async (req, res) => {
        const classroom = new ClassroomEntity_1.ClassroomEntity();
        const data = await ClassroomEntity_1.ClassroomEntity.createQueryBuilder('classroom')
            .leftJoinAndSelect("classroom.mediaConstraints", "mediaConstraints")
            .where("classroom.classId=:classId", { classId: 'asdft567890' })
            .getOne();
        console.log('classroom/list: => ', data);
        const rooms = await ClassroomEntity_1.ClassroomEntity.find();
        res.status(200).send(rooms);
    });
    roomRouter.get('/delete/:id', async (req, res) => {
        const roomId = req.params.id;
        await ClassroomEntity_1.ClassroomEntity.delete({ classId: roomId });
        res.status(200).send({ result: 'OK' });
    });
    roomRouter.get('/detail/:id', async (req, res) => {
        const roomId = req.params.id;
        let dbRoom = await ClassroomEntity_1.ClassroomEntity.findOne({ id: roomId });
        if (dbRoom) {
            res.status(200).send(dbRoom);
        }
        else {
            res.status(404).send(`Room ${roomId} do not existed!`);
        }
    });
    roomRouter.get('/api/get-rooms', (req, res, next) => {
        const rooms = [];
        console.log(Classrooms_1.Classrooms.values());
        for (const [_, room] of Classrooms_1.Classrooms) {
            const __room = {
                inviteMode: room.inviteMode,
                joinMode: room.joinMode,
                chatMode: room.chatMode,
                classId: room.classId,
                classname: room.classname,
                conferenceMode: room.conferenceMode,
                media: room.getMediaOption(),
                members: room.getMembers()
            };
            rooms.push(__room);
        }
        res.send(rooms);
    });
    return roomRouter;
}
exports.recordingRouter = recordingRouter;
